<template>
  <div>
    <div class="hkv">
      <div class="left">
        <el-carousel :interval="4000" type="card" height="200px">
          <el-carousel-item v-for="item in 6" :key="item">
            <h3 class="medium">{{ item }}</h3>
          </el-carousel-item>
        </el-carousel>
        <div style="height:400px;width:100%;">
          <div id="divPlugin" class="plugin" />
        </div>
      </div>
      <div class="right">
        <el-card shadow="never">
          <div slot="header" class="clearfix">
            <span><i class="el-icon-video-camera-solid" /> 云台控制</span>
          </div>
          <div>
            <el-row :gutter="30">
              <el-col :span="12">
                <el-row :gutter="0">
                  <el-col :span="8" class="menu">
                    <el-button type="primary" size="small" icon="el-icon-top-left" @mousedown.native="mouseDownPTZControl(5)" @mouseup.native="mouseUpPTZControl" />
                  </el-col>
                  <el-col :span="8" class="menu">
                    <el-button type="primary" size="small" icon="el-icon-top" @mousedown.native="mouseDownPTZControl(1)" @mouseup.native="mouseUpPTZControl" />
                  </el-col>
                  <el-col :span="8" class="menu">
                    <el-button type="primary" size="small" icon="el-icon-top-right" @mousedown.native="mouseDownPTZControl(7)" @mouseup.native="mouseUpPTZControl" />
                  </el-col>
                  <el-col :span="8" class="menu">
                    <el-button type="primary" size="small" icon="el-icon-back" @mousedown.native="mouseDownPTZControl(3)" @mouseup.native="mouseUpPTZControl" />
                  </el-col>
                  <el-col :span="8" class="menu">
                    <el-button type="primary" size="small" icon="el-icon-refresh" @mousedown.native="mouseDownPTZControl(9)" @mouseup.native="mouseUpPTZControl" />
                  </el-col>
                  <el-col :span="8" class="menu">
                    <el-button type="primary" size="small" icon="el-icon-right" @mousedown.native="mouseDownPTZControl(4)" @mouseup.native="mouseUpPTZControl" />
                  </el-col>
                  <el-col :span="8" class="menu">
                    <el-button type="primary" size="small" icon="el-icon-bottom-left" @mousedown.native="mouseDownPTZControl(6)" @mouseup.native="mouseUpPTZControl" />
                  </el-col>
                  <el-col :span="8" class="menu">
                    <el-button type="primary" size="small" icon="el-icon-bottom" @mousedown.native="mouseDownPTZControl(2)" @mouseup.native="mouseUpPTZControl" />
                  </el-col>
                  <el-col :span="8" class="menu">
                    <el-button type="primary" size="small" icon="el-icon-bottom-right" @mousedown.native="mouseDownPTZControl(8)" @mouseup.native="mouseUpPTZControl" />
                  </el-col>
                </el-row>
              </el-col>
              <el-col :span="12">
                <el-row style="text-align:center;">
                  <el-col :span="12" class="menu">
                    <el-button type="primary" size="small" icon="el-icon-zoom-in" />
                  </el-col>
                  <el-col :span="12" class="menu">
                    <el-button type="primary" size="small" icon="el-icon-zoom-out" />
                  </el-col>
                  <el-col :span="12" class="menu">
                    <el-button type="primary" size="small" icon="el-icon-connection" />
                  </el-col>
                  <el-col :span="12" class="menu">
                    <el-button type="primary" size="small" icon="el-icon-copy-document" />
                  </el-col>
                  <el-col :span="12" class="menu">
                    <el-button type="primary" size="small"><i class="fa fa-qq" aria-hidden="true" /></el-button>
                  </el-col>
                  <el-col :span="12" class="menu">
                    <el-button type="primary" size="small"><i class="fa fa-weixin" aria-hidden="true" /></el-button>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </div>
        </el-card>
        <el-card shadow="never">
          <div slot="header" class="clearfix">
            <span><i class="el-icon-view" /> 预览</span>
          </div>
          <div>
            <el-row style="text-align:center;">
              <el-col :span="12" class="menu">
                <el-button style="width:110px;" type="primary" size="small" @click.native="capture">抓图</el-button>
              </el-col>
              <el-col :span="12" class="menu">
                <el-button style="width:110px;" type="primary" size="small" @click.native="full">全屏</el-button>
              </el-col>
              <el-col :span="12" class="menu">
                <el-button style="width:110px;" type="primary" size="small" @click.native="startElectron">启用电子放大</el-button>
              </el-col>
              <el-col :span="12" class="menu">
                <el-button style="width:110px;" type="primary" size="small" @click.native="closeElectron">禁用电子放大</el-button>
              </el-col>
              <el-col :span="12" class="menu">
                <el-button style="width:110px;" type="primary" size="small" @click.native="start3D">启用3D放大</el-button>
              </el-col>
              <el-col :span="12" class="menu">
                <el-button style="width:110px;" type="primary" size="small" @click.native="close3D">禁用3D放大</el-button>
              </el-col>
            </el-row>
          </div>
        </el-card>
        <el-card shadow="never">
          <div slot="header" class="clearfix">
            <span><i class="el-icon-setting" /> 本地配置</span>
          </div>
          <div>
            <el-row style="text-align:center;margin-top:20px;">
              <el-col :span="24" class="menu">
                预览抓图保存路径
                <el-button type="primary" size="small" @click="handleGetPath('snapPath')">浏览</el-button>
                {{ snapPath }}
              </el-col>
              <el-col :span="24" class="menu">
                <el-row style="text-align:center;margin-top:30px;">
                  <el-col :span="12">
                    <el-button style="width:50%;" type="primary" size="small" @click.native="capture">获取</el-button>
                  </el-col>
                  <el-col :span="12">
                    <el-button style="width:50%;" type="primary" size="small" @click="setLocalCfg">设置</el-button>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </div>
    </div>
    <el-button type="primary" :loading="loginLoading" @click="onLogin">登录</el-button>
    <el-button type="primary" :loading="startPlayLoading" @click="clickStartRealPlay">开始预览</el-button>
    <el-button type="primary" @click="clickStopRealPlay">停止预览</el-button>
    <el-button type="primary" @click="onLogout">退出</el-button>
  </div>
</template>

<script>
import { WebVideoCtrl } from '../../../public/webVideoCtrl.js'

export default {

  data() {
    return {
      hkvInfo: {
        ip: '122.205.95.252', // 海康威视摄像头/硬盘录像机的ip地址
        port: '81', // 海康威视摄像头/硬盘录像机的端口
        username: 'admin', // 海康威视摄像头/硬盘录像机的用户名
        password: 'abcd1234', // 海康威视摄像头/硬盘录像机的密码
        channels: []// 海康威视摄像头/硬盘录像机的通道
      },
      mySelectWnd: 0, // 当前选中的窗口
      g_bPTZAuto: false,
      iProtocol: 1,
      loginLoading: false,
      startPlayLoading: false,
      iStreamType: 1,
      bZeroChannel: false,
      iRtspPort: 0,
      snapPath: ''
    }
  },
  created: function() {
  },
  mounted: function() {
    this.videoInitPlugin() // 初始化video界面
  },

  destroyed: function() {
    this.clickStopRealPlay()
    this.onLogout()
  },
  methods: {
    onLogin() {
      var that = this
      that.loginLoading = true

      // 登录设备
      WebVideoCtrl.I_Login(that.hkvInfo.ip, that.iProtocol, that.hkvInfo.port, that.hkvInfo.username, that.hkvInfo.password, {
        async: false,
        success: function(xmlDoc) {
          // console.log('xmlDoc2', xmlDoc);//不能删除
          // TODO 获取通道信息
          that.getChannelInfo()
          that.getDevicePort(that.hkvInfo.ip + '_' + that.hkvInfo.port)
          that.loginLoading = false

          that.$message({
            showClose: true,
            message: '登录成功',
            type: 'success'
          })
        },
        error: function() {
          that.loginLoading = false
          that.$message({
            showClose: true,
            message: '登录失败',
            type: 'error'
          })
        }
      })
    },
    onLogout() {
      this.hkvInfo.channels = []
      var szDeviceIdentify = this.hkvInfo.ip + '_' + this.hkvInfo.port
      var iRet = WebVideoCtrl.I_Logout(szDeviceIdentify)
      if (iRet == 0) {
        this.$message({
          showClose: true,
          message: '退出成功',
          type: 'success'
        })
      } else {
        this.$message({
          showClose: true,
          message: '退出失败',
          type: 'error'
        })
      }
    },
    clickStartRealPlay() {
      // 开始预览
      var that = this
      that.startPlayLoading = true
      var szDeviceIdentify = that.hkvInfo.ip + '_' + that.hkvInfo.port

      var j = that.hkvInfo.channels.length > 4 ? 4 : that.hkvInfo.channels.length
      for (var i = 0; i < j; i++) {
        setTimeout(that.startRealPlay(szDeviceIdentify, i, that.hkvInfo.channels[i]), 500)
      }
      that.startPlayLoading = false
    },
    videoInitPlugin: function() {
      var iRet = WebVideoCtrl.I_CheckPluginInstall()
      if (iRet === -1) {
        alert('您还未安装过插件，双击开发包目录里的WebComponentsKit.exe安装')
        return
      }
      this.initPlugin()
    },
    initPlugin: function() {
      var that = this

      WebVideoCtrl.I_InitPlugin(500, 300, {
        bWndFull: true, // 是否支持单窗口双击全屏，默I_CheckPluginInstall
        iWndowType: 2,
        myCbSelWnd: function(xmlStr) { // 自己新增的方法
          var jsonObj = that.$x2js.xml2js(xmlStr)
          that.mySelectWnd = jsonObj.RealPlayInfo.SelectWnd
          var szInfo = '当前选择的窗口编号：' + that.mySelectWnd
          console.log(szInfo)
        },
        cbInitPluginComplete: function() {
          WebVideoCtrl.I_InsertOBJECTPlugin('divPlugin')
          // 检查插件是否最新
          if (WebVideoCtrl.I_CheckPluginVersion() === -1) {
            alert('检测到新的插件版本，双击开发包目录里的WebComponentsKit.exe升级！')
            return
          }
        }
      })
    },
    getDevicePort: function(szDeviceIdentify) {
      var oPort = WebVideoCtrl.I_GetDevicePort(szDeviceIdentify)
      this.iRtspPort = oPort.iRtspPort
    },
    startRealPlay: function(szDeviceIdentify, iWndIndex, iChannelID) {
      var that = this
      WebVideoCtrl.I_StartRealPlay(szDeviceIdentify, {
        iRtspPort: that.iRtspPort,
        iWndIndex: iWndIndex,
        iStreamType: 1,
        iChannelID: iChannelID,
        bZeroChannel: that.bZeroChannel,
        success: function() {
          that.$notify({
            title: '成功',
            message: '开始预览通道' + iChannelID + '成功',
            type: 'success'
          })
        },
        error: function(status, xmlDoc2) {
          console.log(xmlDoc2)// 不能删除
          that.$notify({
            title: '失败',
            message: '开始预览通道' + iChannelID + '失败',
            type: 'error'
          })
          if (status === 403) {
            console.log('szInfo 设备不支持Websocket取流！')
          } else {
            console.log('开始预览失败 ', status, xmlDoc2)
          }
        }
      })
    },
    clickStopRealPlay: function() {
      var j = this.hkvInfo.channels.length > 4 ? 4 : this.hkvInfo.channels.length
      for (var i = 0; i < j; i++) {
        setTimeout(this.stopRealPlay(i), 1000)
      }
    },
    stopRealPlay: function(iWndIndex) {
      var that = this
      WebVideoCtrl.I_Stop({
        iWndIndex: iWndIndex,
        success: function() {
          that.$notify({
            title: '成功',
            message: '停止预览窗口' + iWndIndex + '成功',
            type: 'success'
          })
        },
        error: function() {
          that.$notify({
            title: '失败',
            message: '停止预览窗口' + iWndIndex + '失败',
            type: 'error'
          })
        }
      })
    },
    // 获取通道，实际上可以根据自己的项目，获取数字通道，模拟通道，零通道中的一个或多个，不用全部获取（提高效率）
    getChannelInfo: function() {
      var that = this
      var szDeviceIdentify = this.hkvInfo.ip + '_' + this.hkvInfo.port
      // debugger
      // 数字通道
      that.hkvInfo.channels = []
      WebVideoCtrl.I_GetDigitalChannelInfo(szDeviceIdentify, {
        async: false,
        mysuccess: function(xmlStr) {
          console.log('mysuccess I_GetDigitalChannelInfo: ', xmlStr)
          var jsonObj = that.$x2js.xml2js(xmlStr)
          var list = jsonObj.InputProxyChannelStatusList.InputProxyChannelStatus
          for (var x = 0; x < list.length; x++) {
            that.hkvInfo.channels.push(list[x].id)
          }
        },
        success: function(xmlDoc) {
        },
        error: function(status, xmlDoc) {
          console.log('获取数字通道失败')
        }
      }
      )
      // TODO 模拟通道
      // 模拟通道
      WebVideoCtrl.I_GetAnalogChannelInfo(szDeviceIdentify, {
        async: false,
        mysuccess: function(xmlStr) {
          var jsonObj = that.$x2js.xml2js(xmlStr)
          console.log('模拟通道mysuccess', xmlStr)
          // var list = jsonObj.VideoInputChannelList;
          // for (var x = 0; x < list.length; x++) {
          //   that.hkvInfo.channels.push(list[x].VideoInputChannel.id);
          // }
          var id = jsonObj.VideoInputChannelList.VideoInputChannel.id
          that.hkvInfo.channels.push(id)
        },
        success: function(xmlStr) {
          console.log('模拟通道success', xmlStr)
        },
        error: function(status, xmlDoc) {
          console.log('模拟通道error', xmlDoc)
        }
      })
      // TODO 零通道
    },
    mouseDownPTZControl: function(iPTZIndex) {
      var oWndInfo = WebVideoCtrl.I_GetWindowStatus(this.mySelectWnd)

      if (oWndInfo !== null) {
        if (iPTZIndex === 9 && this.g_bPTZAuto) {
          iPTZSpeed = 0
        } else {
          this.g_bPTZAuto = false
        }

        WebVideoCtrl.I_PTZControl(iPTZIndex, false, {
          iPTZSpeed: 4,
          mysuccess: function(xmlStr) {
            console.log('I_PTZControl', xmlStr)
            if (iPTZIndex === 9 && this.g_bPTZAuto) {
              console.log(oWndInfo.szDeviceIdentify + ' 停止云台成功！mouseDown')
            } else {
              console.log(oWndInfo.szDeviceIdentify + ' 开启云台成功！mouseDown')
            }
            if (iPTZIndex === 9) {
              this.g_bPTZAuto = !this.g_bPTZAuto
            }
          },
          error: function(status, xmlDoc) {
            console.log(oWndInfo.szDeviceIdentify + ' 开启云台失败！mouseDown', status, xmlDoc)
          }
        })
      }
    },
    mouseUpPTZControl: function() {
      var oWndInfo = WebVideoCtrl.I_GetWindowStatus(this.mySelectWnd)
      if (oWndInfo !== null) {
        WebVideoCtrl.I_PTZControl(1, true, {
          mysuccess: function(xmlStr) {
            console.log(oWndInfo.szDeviceIdentify + ' 停止云台成功！mouseUp', xmlStr)
          },
          error: function(status, xmlDoc) {
            console.log(oWndInfo.szDeviceIdentify + ' 停止云台失败！mouseUp', status, xmlDoc)
          }
        })
      }
    },
    capture() { // 抓图
      var number = WebVideoCtrl.I_CapturePic('capture.jpg', {
        iWndowType: this.mySelectWnd,
        bDateDir: true
      })
      if (number == 0) {
        alert('抓图成功')
      } else {
        alert('抓图失败')
      }
    },
    full() {
      WebVideoCtrl.I_FullScreen(true)
    },
    startElectron() {
      var number = WebVideoCtrl.I_EnableEZoom()
      if (number == 0) {
        alert('开启电子放大成功')
      } else {
        alert('开启电子放大失败')
      }
    },
    closeElectron() {
      var number = WebVideoCtrl.I_DisableEZoom()
      if (number == 0) {
        alert('关闭电子放大成功')
      } else {
        alert('关闭电子放大失败')
      }
    },
    start3D() {
      var number = WebVideoCtrl.I_EnableEZoom()
      if (number == 0) {
        alert('开启3D放大成功')
      } else {
        alert('开启3D放大失败')
      }
    },
    close3D() {
      var number = WebVideoCtrl.I_Disable3DZoom()
      if (number == 0) {
        alert('关闭3D放大成功')
      } else {
        alert('关闭3D放大失败')
      }
    },
    getLocalCfg() {
      var xml = WebVideoCtrl.I_GetLocalCfg()
      var jsonObj = this.$x2js.xml2js(xml)
      console.log(jsonObj)
    },
    setLocalCfg() {
      var szLocalCofing = `<CapturePath>${this.snapPath}</CapturePath> `
      var number = WebVideoCtrl.I_SetLocalCfg(szLocalCofing)
      if (number == 0) {
        alert('设置成功')
      } else {
        alert('设置失败')
      }
    },
    handleGetPath(path) {
      /*
                * 该方法只支持IE.
                * 语法：strDir=Shell.BrowseForFolder(Hwnd,Title,Options,[RootFolder])
                * 参数：Hwnd：包含对话框的窗体句柄（handle），一般设置为0
                * Title：将在对话框中显示的说明，为字符串
                * Options：使用对话框的特殊方式，为长整数，一般设置为0
                * RootFolder：（可选的），用来设置浏览的最顶层文件夹，缺省时为“桌面”，可以将其设置为一个路径或“特殊文件夹常数”
                * */
      try {
        let filePath
        const objSrc = new ActiveXObject('Shell.Application').BrowseForFolder(0, '请选择保存路径', 0, '')
        if (objSrc != null) {
          filePath = objSrc.Items().Item().Path
          if (filePath.charAt(0) == ':') {
            alert('请选择文件夹.')
            return false
          }
          this.snapPath = filePath
        }
      } catch (e) {
        alert(e + '请设置IE，Internet选项－安全－自定义级别－将ActiveX控件和插件前3个选项设置为启用，然后再尝试。')
        return false
      }
    }
  }
}
</script>

<style scoped>
.hkv{
    display: flex;
    justify-content: space-between;
}
.left{
    flex: 2;
}
.right{
    flex: 1;
}
.el-carousel__item h3 {
    color: #475669;
    font-size: 18px;
    opacity: 0.75;
    line-height: 300px;
    margin: 0;
  }

  .el-carousel__item:nth-child(2n) {
    background-color: #99a9bf;
  }

  .el-carousel__item:nth-child(2n+1) {
    background-color: #d3dce6;
  }
  .top{
      width: 100%;
      height: 30px;
      display: flex;
      align-items: center;
      font-size: 17px;
      border: 1px ;
  }
</style>
